package com.dragon.controller;

import com.dragon.pojo.Result;
import com.dragon.pojo.User.*;
import com.dragon.service.UserService;
import com.dragon.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 登录接口
     * @param loginInfo 登录信息
     * @return 响应信息
     */
    @PostMapping("login")
    public Result login(@RequestBody LoginInfo loginInfo){
        log.info("用户登录:{}",loginInfo.getIdentifier());
        User user = userService.login(loginInfo);
        if(user != null){
            //自定义信息
            Map<String , Object> claims = new HashMap<>();
            claims.put("id", user.getId());
            claims.put("username",user.getUsername());
            claims.put("nickname",user.getNickname());
            claims.put("permissions",user.getPermissions());

            //使用JWT工具类，生成身份令牌
            String token = JwtUtils.generateJwt(claims);
            log.info("登录成功:{}",user.getUsername());
            return Result.success("登录成功", token);
        }
        log.info("登录失败");
        return Result.error("账号或密码错误",401);
    }

    /**
     * 注册接口
     * @param user User对象
     * @return 响应信息
     */
    @PostMapping("register")
    public Result register(@RequestBody User user){
            log.info("用户注册:{}",user.getUsername());
            userService.register(user);
            return Result.success("注册成功");
    }

    /**
     * 查询用户信息
     * @param request 获取token
     * @return 响应信息
     */
    @GetMapping("userInfo")
    public Result userInfo(HttpServletRequest request) {
        User user = new User();
        Claims claims = (Claims) request.getAttribute("claims");

        user.setId((Integer) claims.get("id"));

        UserInfo userInfo = userService.getUserInfo(user);
        if(userInfo != null){
            return Result.success(userInfo);
        } else {
            return Result.error("用户不存在",410);
        }
    }

    /**
     * 修改用户信息
     * @param request 获取token
     * @param user User
     * @return 响应信息
     */
    @PutMapping("userInfo")
    public Result userInfo(HttpServletRequest request, @RequestBody User user) {
        Claims claims = (Claims) request.getAttribute("claims");
        user.setId((Integer) claims.get("id"));
        userService.updateUserInfo(user);
        return Result.success("修改成功");
    }

    /**
     * 修改密码
     * @param request 获取token
     * @param info UpdatePasswordInfo
     * @return 响应信息
     */
    @PatchMapping("updatePwd")
    public Result updatePwd(HttpServletRequest request, @RequestBody UpdatePasswordInfo info) {
        User user = new User();

        Claims claims = (Claims) request.getAttribute("claims");
        user.setId((Integer) claims.get("id"));
        try {
            if(info.getOld_pwd().equals(userService.getPassword(user))){
                user.setPassword(info.getNew_pwd());
                userService.updatePwd(user);
                log.info("用户 {} 密码修改成功",user.getId());
                return Result.success("密码修改成功");
            } else {
                log.info("用户 {} 密码修改失败：旧密码错误",user.getId());
                return Result.error("旧密码错误",401);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 注销账号
     * @param request 获取token
     * @param user User
     * @return 响应信息
     */
    @PostMapping("logout")
    public Result logout(HttpServletRequest request, @RequestBody User user) {
        Claims claims = (Claims) request.getAttribute("claims");
        user.setId((Integer) claims.get("id"));
        if(user.getPassword().equals(userService.getPassword(user))) {
            userService.logout(user);
            log.info("用户 {} 注销成功",user.getId());
            return Result.success("注销成功");
        } else {
            log.info("用户 {} 注销失败：密码错误",user.getId());
            return Result.error("密码错误");
        }
    }

    /**
     * 修改头像
     * @param request 获取token
     * @param avatar 图片文件
     * @return 响应信息
     * @throws IOException IO 异常
     */
    @PutMapping("avatar")
    public Result updateAvatar(HttpServletRequest request, MultipartFile avatar) throws IOException {
        log.info("文件上传，文件名：{}",avatar.getOriginalFilename());

        User user = new User();
        Claims claims = (Claims) request.getAttribute("claims");
        user.setId((Integer) claims.get("id"));

        return Result.success("上传成功",userService.updateAvatar(user, avatar));
    }

    /**
     * 查询用户列表
     * @param request 获取token
     * @param info UserSelectInfo
     * @return 响应信息
     */
    @GetMapping("list")
    public Result getUserList(HttpServletRequest request, UserSelectInfo info) {
        Claims claims = (Claims) request.getAttribute("claims");
        if(claims.get("permissions").equals("admin")){
            return Result.success(userService.getUserList(info));
        }
        return Result.error("没有权限",403);
    }
}
